<script lang="ts" setup>
/**
 * axios axios 配置
 * myMixin 页面公共方法
 */
let axios: any = inject('$axios');

/**
 * searchForm 搜索value
 * searchOptions 搜索配置
 * handelSearch 搜索暴露方法
 */
const searchItem = ref(null);
const searchOptions = reactive([
  {
    label: '手机号',
    value: '',
    key: 'mobile',
    placeholder: '请输入手机号',
    options: [],
    type: 'input',
    size: 5,
  },
  {
    label: '微信号',
    value: '',
    key: 'number',
    placeholder: '请输入微信号',
    options: [],
    type: 'input',
    size: 5,
  },
  {
    label: '发布地区',
    value: '',
    key: 'area',
    placeholder: '请选择信息发布地区',
    options: [],
    type: 'city',
    size: 5,
  },
]);
const searchForm = ref();
const handelSearch = (params) => {
  searchForm.value = Object.assign(
    {
      mobile: '', // 手机号
      number: '', // 微信号
    },
    params,
  );
  // 省市区数据
  if (params.area.length) {
    searchForm.value.area_province_id = params.area[0];
    searchForm.value.area_city_id = params.area[1];
    searchForm.value.area_district_id = params.area[2];
    delete searchForm.value.area;
  }
  getTableList();
};

/**
 * 列表表格：
 * tableOptions 表格组件配置
 * columns 表格columns配置
 * tableData 表格数据参数
 * loadingTable 加载表格数据loading
 * getTableList 获取表格数据方法
 * handlePaginationChange 切换currentPage或切换pageSize
 */
const tableOptions = reactive({
  showPagination: true,
  paginationConfig: {
    total: 10,
    currentPage: 1,
    pageSize: 10,
  },
});
const columns = ref([
  { prop: 'id', label: '用户ID', align: 'center', width: '60' },
  {
    label: '用户名',
    align: 'center',
    width: '120',
    render: ({ row }) => {
      return h('span', '微信用户');
    },
  },
  {
    prop: 'nickname',
    label: '微信昵称',
    width: '120',
    align: 'center',
    render: ({ row }) => {
      return h('span', row.nickname || '-');
    },
  },
  { prop: 'number', label: '微信号', align: 'center' },
  {
    label: '已绑定地区',
    align: 'center',
    width: '200',
    render: ({ row }) => {
      if (!areaOptions.value) return;
      let arr = [];
      buildTree(areaOptions.value).forEach((item) => {
        if (item.code == row.area_province_id) arr.push(item.name);
        if (item.code == row.area_city_id) arr.push(item.name);
        if (item.code == row.area_district_id) arr.push(item.name);
      });
      let str = '';
      if (arr.length) {
        arr.forEach((item, index) => {
          if (index == arr.length - 1) {
            str += `${item}`;
          } else {
            str += `${item}、`;
          }
        });
      }
      return h('span', str);
    },
  },
  { prop: 'mobile', label: '手机号', align: 'center', width: '120' },
  {
    label: '信息完善',
    width: '120',
    align: 'center',
    render: ({ row }) => {
      return h(
        ElTag,
        { effect: 'dark', type: row.style_msg == 1 ? 'success' : 'danger', onClick: () => handelStyleMsg(row) },
        row.style_msg == 1 ? '已完善' : '催促',
      );
    },
  },
  {
    label: '用户状态',
    align: 'center',
    render: ({ row }) => {
      return h(
        ElTag,
        { effect: 'dark', type: row.status == 1 ? 'success' : 'danger' },
        row.status == 1 ? '正常' : '已禁用',
      );
    },
  },
  {
    prop: 'created_at',
    label: '创建时间',
    type: 'date',
    align: 'center',
    width: '170',
  },
  {
    prop: 'updated_at',
    label: '最后登录时间',
    type: 'date',
    align: 'center',
    width: '170',
  },
  {
    label: '操作',
    align: 'center',
    width: '120',
    render: ({ row }) => {
      let arr = [
        {
          name: '禁用',
          type: 'primary',
          icon: '',
          command: handleDisable,
        },
        {
          name: '启用',
          type: 'primary',
          icon: '',
          command: handleEnable,
        },
        {
          name: '名片',
          type: 'primary',
          icon: '',
          command: handleCard,
        },
      ];
      row.status == 1 ? arr.splice(1, 1) : arr.splice(0, 1);
      let showButton = arr.map((item) => {
        return h(
          ElButton,
          {
            type: item.type,
            icon: item.icon,
            text: true,
            style: {
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'start',
              height: '25px',
              width: '50%',
              margin: '0  5px',
              padding: 0,
            },
            onClick: () => item.command(row),
          },
          item.name,
        );
      });
      return h(
        'div',
        {
          style: {
            textAlign: 'center',
            width: '70%',
            height: '100%',
            margin: '0 auto',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          },
        },
        showButton,
      );
    },
  },
]);
const tableData = ref([]);
const loadingTable = ref(false);
const getTableList = async (page?: any) => {
  loadingTable.value = true;
  let params = Object.assign(
    {
      page: page ? page : tableOptions.paginationConfig.currentPage,
      limit: tableOptions.paginationConfig.pageSize,
    },
    searchForm.value,
  );
  let res = await axios.getWechatUserList(params);
  loadingTable.value = false;
  if (res.data.code != 200)
    return ElMessage({
      message: res.data.message,
      type: 'error',
    });
  tableData.value = res.data.data.list;
  tableOptions.paginationConfig = {
    total: Number(res.data.data.pageData.count),
    currentPage: Number(res.data.data.pageData.page),
    pageSize: 10,
  };
};
const handlePaginationChange = (currentPage, pageSize) => {
  tableOptions.paginationConfig.currentPage = currentPage;
  tableOptions.paginationConfig.pageSize = pageSize;
  getTableList();
};

/**
 * 表格操作方法
 * handleDisable 启用
 * handleEnable 禁用
 */
const handleDisable = (row) => {
  ElMessageBox.confirm('确认要禁用吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    beforeClose: async (action, instance, done) => {
      if (action == 'confirm') {
        //点击确认请求接口
        //点击确认请求接口
        let res: any = await axios.perfectUserInfo({
          id: row.id,
          status: 2,
        });
        if (res.data.code != 200) return;
        ElMessage({ type: 'success', message: `操作成功` });
        done();
        getTableList();
      } else {
        //点击取消关闭
        done();
      }
    },
  });
};
const handleEnable = (row) => {
  ElMessageBox.confirm('确认要启用吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    beforeClose: async (action, instance, done) => {
      if (action == 'confirm') {
        //点击确认请求接口
        let res: any = await axios.perfectUserInfo({
          id: row.id,
          status: 1,
        });
        if (res.data.code != 200) return;
        ElMessage({ type: 'success', message: `操作成功` });
        done();
        getTableList();
      } else {
        //点击取消关闭
        done();
      }
    },
  });
};

/**
 * 卡片信息
 * dialogCardOpitons 弹窗配置
 * formCardOptions
 * formCard
 * handelDialogCardButton
 */
const dialogCardOpitons = reactive({
  dialogShow: false,
  title: '修改信息',
  width: '35%',
  footButtonList: {
    cancel: {
      type: 'cancel',
      buttonType: 'default',
      btnText: '取 消',
      btnLoading: false,
      btnLoadingText: '',
    },
    success: {
      type: 'success',
      buttonType: 'primary',
      btnText: '提 交',
      btnLoading: false,
      btnLoadingText: '提交中',
    },
  },
});
const formCardOptions = reactive({
  labelWidth: '85px',
  labelPosition: 'left',
});
const formCard: any = ref({
  name: '', // 姓名
  sex: '', // 性别
  area: '', // 地址
  birthday: '', // 出生日期
  job_name: '', // 职位
});
const cardFormRef = ref();
const rulesCard = reactive({
  name: [
    {
      required: true,
      validator: async (rule: any, value: any, callback: any) => {
        if (!value) return callback(new Error('请填写姓名后提交'));
        callback();
      },
      trigger: ['blur'],
    },
  ],
  sex: [
    {
      required: true,
      validator: async (rule: any, value: any, callback: any) => {
        if (!value) return callback(new Error('请选择性别后提交'));
        callback();
      },
      trigger: ['blur'],
    },
  ],
  area: {
    required: true,
    validator: (rule: any, value: any, callback: any) => {
      if (!value) return callback(new Error('请填写地址后提交'));
      callback();
    },
    trigger: ['blur'],
  },
  birthday: {
    required: true,
    validator: (rule: any, value: any, callback: any) => {
      if (!value) return callback(new Error('请选择出生日期'));
      callback();
    },
    trigger: ['blur'],
  },
  job_name: {
    required: true,
    validator: (rule: any, value: any, callback: any) => {
      if (!value) return callback(new Error('请填写职位后提交'));
      callback();
    },
    trigger: ['blur'],
  },
});
const backShowBirthday = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
const editDate = ref();
const handleCard = (row) => {
  editDate.value = row;
  formCard.value = {
    name: row.nickname, // 姓名
    sex: String(row.sex), // 性别
    area: [row.area_province_id, row.area_city_id, row.area_district_id], // 地址
    birthday: backShowBirthday(Number(row.birthday) * 1000), // 出生日期
    job_name: row.job_name, // 职位
  };
  dialogCardOpitons.dialogShow = true;
};
const handelDialogCardButton = (item) => {
  if (item.type == 'cancel') dialogCardOpitons.dialogShow = false;
  if (item.type == 'success') handleCardSuccess('success');
};
const handleCardSuccess = async (type) => {
  cardFormRef.value.validateForm(async (valid) => {
    if (valid) {
      let params = Object.assign(
        {
          id: editDate.value.id,
        },
        formCard.value,
      );
      params.area_province_id = formCard.value.area[0];
      params.area_city_id = formCard.value.area[1];
      params.area_district_id = formCard.value.area[2];
      delete params.area;
      params.birthday = Date.parse(params.birthday) / 1000;
      dialogCardOpitons.footButtonList[type].btnLoading = true;
      let res = await axios.perfectUserInfo(params);
      dialogCardOpitons.footButtonList[type].btnLoading = false;
      if (res.data.code != 200)
        return ElMessage({
          message: res.data.message,
          type: 'error',
        });
      ElMessage({ type: 'success', message: `操作成功` });
      dialogCardOpitons.dialogShow = false;
      getTableList();
    }
  });
};

/**
 * 催促
 * handelStyleMsg
 */
const handelStyleMsg = (row) => {
  if (row.style_msg != 1) {
    ElMessageBox.confirm('确认要催促完善信息吗?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      beforeClose: async (action, instance, done) => {
        if (action == 'confirm') {
          //点击确认请求接口
          let res: any = await axios.getClickUserTask({
            user_id: row.id,
          });
          if (res.data.code != 200) return;
          ElMessage({ type: 'success', message: `催促成功` });
          done();
        } else {
          //点击取消关闭
          done();
        }
      },
    });
  }
}

/**
 * init 初始化方法入口
 *
 */
const areaOptions = ref();
const buildTree = (data) => {
  const result = [];
  function flatten(item) {
    result.push(item);
    if (item._child && item._child.length > 0) {
      item._child.forEach((child) => {
        flatten(child);
      });
    }
  }
  data.forEach((item) => {
    flatten(item);
  });
  return result;
};
const init = async () => {
  // 地区数据
  let cityDate = await axios.getCityChina({
    is_tree: 1,
  });
  areaOptions.value = cityDate.data.data;
  searchItem.value.handelSetOptions(cityDate.data.data, 2);
  getTableList();
};
init();
</script>
<template>
  <div class="task">
    <!-- 搜索 、表格数据 -->
    <pagesLayout pagesType="alone" class="padding-20">
      <template #center>
        <div class="pageslayout">
          <!-- 搜索 -->
          <div class="pageslayoutHeader">
            <SearchItem :searchOptions="searchOptions" @handelSearch="handelSearch" ref="searchItem"></SearchItem>
          </div>
          <!-- 、表格数据 -->
          <div class="pageslayoutContaint" element-loading-text="加载中..." v-loading="loadingTable">
            <Table :columns="columns" :table-data="tableData" :options="tableOptions" style="height: 100%"
              @handel-pagination-change="handlePaginationChange"></Table>
          </div>
        </div>
      </template>
    </pagesLayout>
    <!-- 名片 弹窗 -->
    <Dialog :dialog-object="dialogCardOpitons" @handelDialogButton="handelDialogCardButton">
      <template v-slot:dialogContaint>
        <Form :form-object="formCardOptions" :form="formCard" :rules="rulesCard" ref="cardFormRef">
          <template v-slot:formContaint>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formCard.name" placeholder="请输入您的姓名" />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="formCard.sex" class="m-2" placeholder="请选择您的性别" size="large">
                <el-option value="0" label="未知"></el-option>
                <el-option value="1" label="男"></el-option>
                <el-option value="2" label="女"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="地址" prop="area">
              <el-cascader :options="areaOptions" v-model="formCard.area" placeholder="请选择您的地址" :props="{
              label: 'name',
              value: 'code',
              children: '_child',
            }" />
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker v-model="formCard.birthday" style="width: 100%" type="date" clearable
                placeholder="请输入您的出生日期" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="职位" prop="job_name">
              <el-input v-model="formCard.job_name" placeholder="请输入您的职位" />
            </el-form-item>
          </template>
        </Form>
      </template>
    </Dialog>
  </div>
</template>
<style scoped lang="scss">
.task {
  height: 100%;
}
</style>
